package cn.kailangtu.dataspot.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

public class UsbDeviceReceiver extends BroadcastReceiver {


    private static final String TAG = "UsbDeviceReceiver";
    private UsbDeviceConnectionListener listener;

    public UsbDeviceReceiver(UsbDeviceConnectionListener listener) {
        this.listener = listener;
    }

    public UsbDeviceReceiver() {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        String action = intent.getAction();
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                Log.d(TAG, "USB device attached: " + device.getDeviceName());
                if (listener != null) {
                    listener.onDeviceAttached(device);
                }
            }
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                Log.d(TAG, "USB device detached: " + device.getDeviceName());
                if (listener != null) {
                    listener.onDeviceDetached(device);
                }
            }
        }
    }

    public interface UsbDeviceConnectionListener {
        void onDeviceAttached(UsbDevice device);
        void onDeviceDetached(UsbDevice device);
    }
}